'use strict';

/*
 *  班级管理
 */ 

const classgradeModel = require('../models/classgrade.model');
const userModel = require('../models/user.model');
const httpUtil = require('../utils/http');
const Code = require('../common/error_code');
const Util = require('../utils/hobot_util');

// 班级列表
async function classgrade_list(ctx) {
    const params = ctx.request.body
    if(!params.page_size||!params.page_num){
        return ctx.error(Code.RET_USER_QUERY_ERR_PARAM);
    }
    let cdt = {
    };
    if (params.name) {
        cdt.name = { $regex: params.name };
    }
    if (params.num) {
        cdt.num = { $regex: params.num };
    }
    const classgrades = await Util.pageQuery(params.page_num, params.page_size, classgradeModel,
        cdt, '', '', {_id: -1});
    ctx.success(Code.REQUEST_SUCCESS('查询成功'), {
        page_num: params.page_num,
        page_size: params.page_size,
        total: classgrades.total,
        result: classgrades.results
    });
}

// 新增班级
async function add_classgrade(ctx){
    const params = ctx.request.body
    try{
        if(!params || typeof params !=='object') return ctx.error(Code.REQUEST_ERROR('请填写设备参数'))
        if(!params.name){
            return ctx.error(Code.REQUEST_ERROR('请填写班级名称'))
        }
        if(!params.num){
            return ctx.error(Code.REQUEST_ERROR('请填写班级编号'))
        }
        const data = await classgradeModel.findOne({num:params.num})
        if(data){
            return ctx.error(Code.REQUEST_ERROR('班级编号不能重复'))
        }
        let studentIds = params.student_ids||[]
        studentIds = [...new Set(studentIds)]
        const related_students = []
        for(let id of studentIds){
            const user = await userModel.findById(id)
            if(user&&user.u_tp===5){
                related_students.push({
                    student_id:id,
                    student_avatar:user.u_hp,
                    student_name:user.u_nm,
                    student_num:user.s_num,
                })
            }
        }
        const gradeParams = {
            name: (params.name).trim(),
            num: (params.num||'').trim(),
            related_students
        }
        await classgradeModel.create(gradeParams)
        ctx.success(Code.REQUEST_SUCCESS('添加成功'))
    }catch(err){
        let message = err && err.message
        let msg, others = []
        if(message) {
           [ msg,...others ] = message.split(': ').reverse()
        }
        ctx.error(Code.REQUEST_ERROR(msg||'添加失败'))
    }
}

// 删除班级
async function delete_classgrade(ctx){
    const params = ctx.request.body
    try{
        if(!params || typeof params !=='object' || !params._id) return ctx.error(Code.REQUEST_ERROR('请选择要删除的教室'))
        if(Array.isArray(params._id)){
            for(let id of params._id){
                const data = await classgradeModel.findOneAndRemove({_id:id}) 
            }
        }else{
            const data = await classgradeModel.findOneAndRemove({_id:params._id})
        }
        return ctx.success(Code.REQUEST_SUCCESS('删除成功'))
    }catch(err){
        return ctx.error(Code.REQUEST_ERROR('删除失败'))
    }
}

// 更新班级
async function update_classgrade(ctx){
    const params = ctx.request.body
    if(!params || typeof params !=='object') return ctx.error(Code.REQUEST_ERROR('请填写设备参数'))
        if(!params._id){
            return ctx.error(Code.REQUEST_ERROR('请选择要更新的班级'))
        }
        if(!params.name){
            return ctx.error(Code.REQUEST_ERROR('请填写班级名称'))
        }
        if(!params.num){
            return ctx.error(Code.REQUEST_ERROR('请填写班级编号'))
        }
        const classgrade = await classgradeModel.findById(params._id)
        if(!classgrade){
            return ctx.error(Code.REQUEST_ERROR('该班级不存在'))
        }
        const data = await classgradeModel.findOne({
            _id:{$ne:params._id},
            num:params.num
        })
        if(data){
            return ctx.error(Code.REQUEST_ERROR('班级编号不能重复'))
        }
        let studentIds = params.student_ids||[]
        studentIds = [...new Set(studentIds)]
        const related_students = []
        for(let id of studentIds){
            const user = await userModel.findById(id)
            if(user&&user.u_tp===5){
                related_students.push({
                    student_id:id,
                    student_avatar:user.u_hp,
                    student_name:user.u_nm,
                    student_num:user.s_num,
                })
            }
        }
        const gradeParams = {
            name: (params.name).trim(),
            num: (params.num||'').trim(),
            related_students
        }
        await classgradeModel.findByIdAndUpdate(params._id, gradeParams)
        ctx.success(Code.REQUEST_SUCCESS('更新成功'))
}


exports.classgrade_list = classgrade_list
exports.add_classgrade = add_classgrade
exports.delete_classgrade = delete_classgrade
exports.update_classgrade = update_classgrade